import 'dart:convert';
import 'package:e_reception_flutter/common_widgets/common_confirm_cancel_dialog/common_confirm_cancel_dialog.dart';
import 'package:e_reception_flutter/net/net_api.dart';
import 'package:e_reception_flutter/singleton/theme_repository/theme_repository.dart';
import 'package:e_reception_flutter/singleton/user_repository/user_repository.dart';
import 'package:e_reception_flutter/ui/smart_home/event/refresh_smart_home_category_event.dart';
import 'package:e_reception_flutter/ui/smart_home/event/refresh_smart_home_index_event.dart';
import 'package:e_reception_flutter/ui/smart_home/publish/smart_home_folder_detail_response_bean.dart';
import 'package:e_reception_flutter/ui/smart_home/publish/smart_home_store_details_page.dart';
import 'package:e_reception_flutter/ui/smart_home/smart_home_category_response_bean.dart';
import 'package:e_reception_flutter/ui/smart_home/smart_home_store_image_detail_response_bean.dart';
import 'package:e_reception_flutter/ui/smart_home/smart_home_terminal_list_response_bean.dart';
import 'package:e_reception_flutter/utils/router_utils.dart';
import 'package:e_reception_flutter/utils/vg_http_utils.dart';
import 'package:e_reception_flutter/utils/vg_hud_utils.dart';
import 'package:e_reception_flutter/utils/vg_toast_utils.dart';
import 'package:e_reception_flutter/vg_widgets/vg_place_holder_status_widget/vg_place_holder_status_widget.dart';
import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
import 'package:vg_base/vg_arch_lib.dart';
import 'package:vg_base/vg_base_callback.dart';
import 'package:vg_base/vg_evnet_bus_lib.dart';
import 'package:vg_base/vg_sp_lib.dart';
import 'package:vg_base/vg_string_util_lib.dart';
import '../../app_main.dart';


class SmartHomeStoreDetailCommonViewModel extends BaseViewModel {


  ValueNotifier<int> totalValueNotifier;
  ValueNotifier<PlaceHolderStatusType> statusTypeValueNotifier;
  ValueNotifier<StorePicInfoBean> imageDetailValueNotifier;
  ValueNotifier<TerminalListDataBean> terminalListValueNotifier;
  ValueNotifier<SmartHomeFolderDetailDataBean> folderDetailDataValueNotifier;


  SmartHomeStoreDetailCommonViewModel(BaseState<StatefulWidget> state,) : super(state){
    statusTypeValueNotifier = ValueNotifier(PlaceHolderStatusType.loading);
    totalValueNotifier = ValueNotifier(null);
    imageDetailValueNotifier = ValueNotifier(null);
    terminalListValueNotifier = ValueNotifier(null);
    folderDetailDataValueNotifier = ValueNotifier(null);

  }
  
  

  ///获取文件夹or动态详情
  void getFolderDetail(BuildContext context, String shid, String sfid, String flg, String picid, Function(SmartHomeFolderDetailDataBean folderDetailData) onGetData){
    if(StringUtils.isEmpty(shid) || StringUtils.isEmpty(sfid)){
      VgToastUtils.toast(context, "门店数据异常");
      return;
    }
    String cacheKey = NetApi.GET_SMART_HOME_FOLDER_DETAILS + (UserRepository.getInstance().getCacheKeySuffix()?? "")
        + shid + sfid + flg + picid;
    ///获取缓存数据
    bool useCacheFlag = false;
    Future<String> future = SharePreferenceUtil.getString(cacheKey);
    future.then((jsonStr){
      if(!StringUtils.isEmpty(jsonStr)){
        print("获取文件夹or动态详情详情：" + cacheKey + "   " + jsonStr);
        Map map = json.decode(jsonStr);
        SmartHomeFolderDetailDataBean bean = SmartHomeFolderDetailDataBean.fromMap(map);
        if(bean != null){
          if(!isStateDisposed){
            onGetData.call(bean);
            useCacheFlag = true;
          }
          loading(false);
        }
        getFolderDetailOnLine(useCacheFlag, cacheKey, shid, sfid, flg, picid, onGetData);
      }else{
        getFolderDetailOnLine(useCacheFlag, cacheKey, shid, sfid, flg, picid, onGetData);
      }
    });

  }

  void getFolderDetailOnLine(bool useCacheFlag, String cacheKey,
      String shid, String sfid, String flg, String picid,
      Function(SmartHomeFolderDetailDataBean folderDetailData) onGetData){

    VgHttpUtils.get(NetApi.GET_SMART_HOME_FOLDER_DETAILS, params: {
      "authId":UserRepository.getInstance().authId ?? "",
      "shid":shid ?? "",
      "sfid":sfid ?? "",
      "flg":flg ?? "",
      "picid":picid ?? "",
    },callback: BaseCallback(
        onSuccess: (val){
          SmartHomeFolderDetailResponseBean bean =
          SmartHomeFolderDetailResponseBean.fromMap(val);
          if(!isStateDisposed){
            if(bean != null && bean.data != null){
              if(!useCacheFlag){
                //未使用缓存，则使用网络数据
                onGetData.call(bean?.data);
              }
              //更新缓存
              SharePreferenceUtil.putString(cacheKey, json.encode(bean.data));
            }
          }
          loading(false);
        },
        onError: (msg){
          loading(false);
          VgToastUtils.toast(AppMain.context, msg);
        }
    ));
  }


  void getFolderDetailWithValueNotifier(String shid, String sfid, String flg, String picid,
      Function(SmartHomeFolderDetailDataBean folderDetailData) onGetData){
    String cacheKey = NetApi.GET_SMART_HOME_FOLDER_DETAILS + (UserRepository.getInstance().getCacheKeySuffix()?? "")
        + shid + sfid + flg + picid;
    VgHttpUtils.get(NetApi.GET_SMART_HOME_FOLDER_DETAILS, params: {
      "authId":UserRepository.getInstance().authId ?? "",
      "shid":shid ?? "",
      "sfid":sfid ?? "",
      "flg":flg ?? "",
      "picid":picid ?? "",
    },callback: BaseCallback(
        onSuccess: (val){
          SmartHomeFolderDetailResponseBean bean =
          SmartHomeFolderDetailResponseBean.fromMap(val);
          if(!isStateDisposed){
            if(bean != null && bean.data != null){
                //未使用缓存，则使用网络数据
                onGetData.call(bean?.data);
              //更新缓存
              SharePreferenceUtil.putString(cacheKey, json.encode(bean.data));
            }
          }
          loading(false);
        },
        onError: (msg){
          loading(false);
          VgToastUtils.toast(AppMain.context, msg);
        }
    ));
  }


  ///删除动态/文件夹
  void deleteFolder(BuildContext context, String shid, String scid, String sfid, String videoId, {String parentScid}){
    VgHudUtils.show(context, "请稍后");
    VgHttpUtils.post(NetApi.GET_SMART_HOME_DELETE_FOLDER, params: {
      "authId":UserRepository.getInstance().authId ?? "",
      "shid":shid??"",
      "sfid":sfid??"",
    },callback: BaseCallback(
        onSuccess: (val){
          if(StringUtils.isNotEmpty(videoId)){
              deleteVodVideoFile(videoId);
          }
          VgEventBus.global.send(new RefreshSmartHomeIndexEvent());
          if(StringUtils.isNotEmpty(parentScid) ){
            VgEventBus.global.send(new RefreshSmartHomeCategoryEvent(id:parentScid));
          }else{
            VgEventBus.global.send(new RefreshSmartHomeCategoryEvent(id:scid));
          }
          VgHudUtils.hide(context);
          RouterUtils.pop(context);
        },
        onError: (msg){
          loading(false);
          VgToastUtils.toast(AppMain.context, msg);}
    ));
  }



  ///获取图片详情
  void getImageDetail(BuildContext context, String picid, Function(StorePicInfoBean picInfo) onGetData){
    if(StringUtils.isEmpty(picid)){
      VgToastUtils.toast(context, "门店数据异常");
      return;
    }
    String cacheKey = NetApi.GET_STORE_ONE_PIC_DETAIL + (UserRepository.getInstance().authId?? "")
        + picid;
    ///获取缓存数据
    Future<String> future = SharePreferenceUtil.getString(cacheKey);
    future.then((jsonStr){
      if(!StringUtils.isEmpty(jsonStr)){
        print("获取图片详情：" + cacheKey + "   " + jsonStr);
        Map map = json.decode(jsonStr);
        SmartHomeStoreImageDetailResponseBean bean = SmartHomeStoreImageDetailResponseBean.fromMap(map);
        if(bean != null){
          if(!isStateDisposed){
            statusTypeValueNotifier?.value = null;
            imageDetailValueNotifier?.value = bean?.data?.storePicInfo;
            onGetData.call(bean?.data?.storePicInfo);
          }
          loading(false);
        }
        getImageDetailOnLine(picid, cacheKey, bean, onGetData);
      }else{
        getImageDetailOnLine(picid, cacheKey, null, onGetData);
      }
    });
  }


  ///网络获取最新图片详情
  void getImageDetailOnLine(String picid, String cacheKey, SmartHomeStoreImageDetailResponseBean bean, Function(StorePicInfoBean picInfo) onGetData){
    VgHttpUtils.get(NetApi.GET_STORE_ONE_PIC_DETAIL, params: {
      "authId":UserRepository.getInstance().authId ?? "",
      "picid":picid ?? "",
    },callback: BaseCallback(
        onSuccess: (val){
          SmartHomeStoreImageDetailResponseBean bean =
          SmartHomeStoreImageDetailResponseBean.fromMap(val);
          if(!isStateDisposed){
            statusTypeValueNotifier?.value = null;
            if(bean != null && bean.data != null && bean?.data?.storePicInfo != null){
              imageDetailValueNotifier?.value = bean?.data?.storePicInfo;
              onGetData.call(bean?.data?.storePicInfo);
            }
          }
          loading(false);
          if(bean!=null){
            SharePreferenceUtil.putString(cacheKey, json.encode(bean));
            print("缓存文件详情：" + cacheKey + "   " + json.encode(bean));
          }
        },
        onError: (msg){
          loading(false);
          VgToastUtils.toast(AppMain.context, msg);
          if(bean == null){
            statusTypeValueNotifier?.value = PlaceHolderStatusType.error;
          }
        }
    ));
  }

  ///删除图片
  void deleteImage(BuildContext context, String picids, String videoIds, String shid){
    VgHudUtils.show(context, "请稍后");
    VgHttpUtils.post(NetApi.DELETE_STORE_PIC, params: {
      "authId":UserRepository.getInstance().authId ?? "",
      "picids":picids??"",
      "shid":shid??""
    },callback: BaseCallback(
        onSuccess: (val){
          if(StringUtils.isNotEmpty(videoIds)){
            List<String> videoIdList = videoIds.split(",");
            videoIdList.forEach((element) {
              deleteVodVideoFile(element);
            });
          }
          VgEventBus.global.send(new RefreshSmartHomeIndexEvent());
          VgEventBus.global.send(new RefreshSmartHomeCategoryEvent());
          VgHudUtils.hide(context);
          RouterUtils.pop(context);
        },
        onError: (msg){
          loading(false);
          VgToastUtils.toast(AppMain.context, msg);}
    ));
  }

  ///删除视频文件
  void deleteVodVideoFile(String videoId){
    if(StringUtils.isEmpty(videoId)){
      return;
    }
    VgHttpUtils.get(NetApi.DELETE_VOD_VIDEO_FILE,params: {
      "videoid":videoId,
    },callback: BaseCallback(
        onSuccess: (val){
          loading(false);
        },
        onError: (msg){
          loading(false);
          VgToastUtils.toast(AppMain.context, msg);
        }
    ));

  }

  ///编辑图片
  void editImage(BuildContext context, String shid, String picid, String backup, String stid, String style, String router){
    VgHudUtils.show(context, "请稍后");
    VgHttpUtils.post(NetApi.EDIT_IMAGE, params: {
      "authId":UserRepository.getInstance().authId ?? "",
      "picid":picid??"",
      "backup":backup??"",
      "stid":stid??"",
      "style":style??"",
      "shid":shid??"",
    },callback: BaseCallback(
        onSuccess: (val){
          VgEventBus.global.send(new RefreshSmartHomeCategoryEvent());
          VgEventBus.global.send(new RefreshSmartHomeIndexEvent());
          VgHudUtils.hide(context);
          RouterUtils.popUntil(context, router??SmartHomeStoreDetailsPage.ROUTER);
        },
        onError: (msg){
          loading(false);
          VgToastUtils.toast(AppMain.context, msg);}
    ));
  }


  ///获取终端
  ///justUsing是否只需要使用中的终端
  void getTerminalList(String shid, String hsnname, {bool justUsing}){
    VgHttpUtils.get(NetApi.SMART_HOME_GET_TERMINAL, params: {
      "authId":UserRepository.getInstance().authId ?? "",
      "shid":shid ?? "",
      "hsnname":hsnname ?? "",
    },callback: BaseCallback(
        onSuccess: (val){
          SmartHomeTerminalListResponseBean bean =
          SmartHomeTerminalListResponseBean.fromMap(val);
          if(!isStateDisposed){
            if(bean != null && bean.data != null){
              if(bean.data.terInfo != null && (justUsing??false)){
                List<TerInfoBean> tempList = new List();
                bean.data.terInfo.forEach((element) {
                  if("01" == element?.terflg){
                    tempList.add(element);
                  }
                });
                bean.data.terInfo = tempList;
              }
              terminalListValueNotifier?.value = bean?.data;
              if(bean.data.terInfo != null && bean.data.terInfo.isNotEmpty){
                statusTypeValueNotifier?.value = null;
              }else{
                statusTypeValueNotifier?.value = PlaceHolderStatusType.empty;
              }
            }else{
              statusTypeValueNotifier?.value = PlaceHolderStatusType.empty;
            }
          }
          loading(false);
        },
        onError: (msg){
          loading(false);
          statusTypeValueNotifier?.value = PlaceHolderStatusType.error;
          VgToastUtils.toast(AppMain.context, msg);}
    ));
  }

  ///智能家居投放至终端
  void pushSmartHome(BuildContext context, String shid, String addHsns, String removeHsns, VoidCallback callback){
    if(StringUtils.isEmpty(shid)){
      return;
    }
    VgHudUtils.show(context, "设置中");
    VgHttpUtils.post(NetApi.SMART_HOME_SET_TERMINAL, params: {
      "authId":UserRepository.getInstance().authId ?? "",
      "shid": shid??"",
      "hsns":addHsns ?? "",
      "removeHsns":removeHsns ?? "",
    },callback: BaseCallback(
        onSuccess: (val){
          VgHudUtils.hide(context);
          VgEventBus.global.send(new RefreshSmartHomeCategoryEvent());
          VgEventBus.global.send(new RefreshSmartHomeIndexEvent());
          VgToastUtils.toast(AppMain.context, "设置成功");
          callback.call();
        },
        onError: (msg){
          VgHudUtils.hide(context);
          VgToastUtils.toast(AppMain.context, msg);}
    ));
  }

  ///智能家居投放到终端-新
  ///00普通 ，01强制
  void setSmartHomeToTerminal(BuildContext context, String force, String shid, String addHsns, String removeHsns, VoidCallback callback){
    if(StringUtils.isEmpty(shid)){
      return;
    }
    VgHudUtils.show(context, "设置中");
    VgHttpUtils.post(NetApi.SMART_HOME_SET_TERMINAL_NEW, params: {
      "authId":UserRepository.getInstance().authId ?? "",
      "force": force??"",
      "shid": shid??"",
      "hsns":addHsns ?? "",
      "removeHsns":removeHsns ?? "",
    },callback: BaseCallback(
        onSuccess: (val){
          VgHudUtils.hide(context);
          VgEventBus.global.send(new RefreshSmartHomeCategoryEvent());
          VgEventBus.global.send(new RefreshSmartHomeIndexEvent());
          VgToastUtils.toast(AppMain.context, "设置成功");
          callback.call();
        },
        onError: (msg)async {
          VgHudUtils.hide(context);
          if (msg.contains("显示屏原有智能家居将被替换")) {
            bool result =
            await CommonConfirmCancelDialog.navigatorPushDialog(context,
              title: "提示",
              content: msg,
              cancelText: "取消",
              confirmText: "确定",
              confirmBgColor: ThemeRepository.getInstance().getPrimaryColor_1890FF(),
              cancelBgColor: Color(0xFFF6F7F9),
              titleColor: ThemeRepository.getInstance().getCardBgColor_21263C(),
              contentColor: ThemeRepository.getInstance().getCardBgColor_21263C(),
              widgetBgColor: Colors.white,
            );
            if (result ?? false) {
              setSmartHomeToTerminal(context, "01", shid, addHsns, removeHsns, callback);
            }
          } else {
            VgToastUtils.toast(context, msg);
          }
        }
    ));
  }

  ///终端更换所属门店---终端更换智能家居
  void terminalChangeSmartHome(BuildContext context, String hsn, String rasid, String shid, VoidCallback callback){
    if(StringUtils.isEmpty(shid)){
      return;
    }
    VgHudUtils.show(context, "设置中");
    VgHttpUtils.post(NetApi.TERMINAL_CHANGE_SMART_HOME, params: {
      "authId":UserRepository.getInstance().authId ?? "",
      "hsn": hsn??"",
      "rasid": rasid??"",
      "shid":shid ?? "",
    },callback: BaseCallback(
        onSuccess: (val){
          VgHudUtils.hide(context);
          VgEventBus.global.send(new RefreshSmartHomeCategoryEvent());
          VgEventBus.global.send(new RefreshSmartHomeIndexEvent());
          VgToastUtils.toast(AppMain.context, "设置成功");
          callback.call();
        },
        onError: (msg)async {
          VgHudUtils.hide(context);
          VgToastUtils.toast(context, msg);
        }
    ));
  }

  void recordSmartHomeLastVisit(String shid,){
    VgHttpUtils.post(NetApi.RECORD_LAST_VISIT_SMART_HOME, params: {
      "authId":UserRepository.getInstance().authId ?? "",
      "shid": shid??"",
    },callback: BaseCallback(
        onSuccess: (val){
          UserRepository.getInstance().setLastShid(shid);
          print("当前shid:" + UserRepository.getInstance().lastshid);
          print("记录最后一次浏览智能家居记录成功");
        },
        onError: (msg) {
          print("记录最后一次浏览智能家居记录失败：" + msg);
        }
    ));
  }



  @override
  void onDisposed() {
    totalValueNotifier?.dispose();
    statusTypeValueNotifier?.dispose();
    imageDetailValueNotifier?.dispose();
    terminalListValueNotifier?.dispose();
    folderDetailDataValueNotifier?.dispose();
  }
  
}
